package com.hooview.quartz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hooview.api.dao.TickerMapper;
import com.hooview.api.entity.*;
import com.hooview.api.service.*;
import com.hooview.api.service.impl.SignServiceImpl;
import com.hooview.contants.Constants;
import com.hooview.utils.CoinwHttpsUtils;
import com.hooview.utils.DateUtils;
import com.hooview.utils.HttpsClientUtils;
import com.sun.org.apache.bcel.internal.generic.FLOAD;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

@Component
public class QuartzMarketService {
    @Resource
    private TickerService tickerService;
    @Resource
    private CoinService coinService;
    @Resource
    private UserService userService;
    @Resource
    private CurrencyExchangeService currencyExchangeService;
    @Resource
    private ProfitRecordService profitRecordService;
    @Resource
    private HyInputService hyInputService;
    @Resource
    private HyProfitService hyProfitService;

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(QuartzMarketService.class);


   // @Scheduled(cron = "0 0/1 * * * ?") //每5分钟执行一次
    public void huobi() {
        String json = "";
        Map param = new HashMap();
        param.put("status", Constants.COIN_STATUS_YES);
        List<Coin> coins = coinService.queryByParams(param);
        Double rate = currencyExchangeService.queryRate("USD", "CNY");
        try {
            for (Coin coin : coins) {
                String code = coin.getCode();
                String api = "https://api.huobipro.com/market/detail/merged?symbol=COINUNIT";
                api = api.replace("COIN", code);
                api = api.replace("UNIT", "usdt");
                api = api.toLowerCase();
                json = HttpsClientUtils.doGet(api);
                if (json != null && !"".equals(json)) {
                    JSONObject object2 = JSON.parseObject(json);
                    JSONObject object = object2.getJSONObject("tick");
                    if (object != null) {
                        String high = object.get("high").toString();
                        System.out.println("huobi high:" + high);
                        String low = object.get("low").toString();
                        String vol = object.get("vol").toString();
                        // String buy = object.get("bid").toString();
                        //String sell = object.get("ask").toString();
                        String last = object.get("close").toString();

                        Ticker ticker = new Ticker();
                        ticker.setHigh(Double.parseDouble(high) * rate);
                        ticker.setLow(Double.parseDouble(low) * rate);
                        ticker.setVol(Double.parseDouble(vol) * rate);
                        // ticker.setBuy(Double.parseDouble(buy) * rate);
                        //ticker.setSell(Double.parseDouble(sell) * rate);
                        ticker.setLast(Double.parseDouble(last) * rate);
                        ticker.setLastUsd(Double.parseDouble(last));
                        ticker.setCoinCode(code);
                        ticker.setDate(new Date());
                        ticker.setSiteName("火币");
                        ticker.setUnitCode("USD");
                        tickerService.insert(ticker);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //币安
    //@Scheduled(cron = "0 0/1 * * * ?") //每5分钟执行一次
    public void biance() {
        String json = "";
        Map param = new HashMap();
        param.put("status", Constants.COIN_STATUS_YES);
        List<Coin> coins = coinService.queryByParams(param);
        Double rate = currencyExchangeService.queryRate("USD", "CNY");
        try {
            for (Coin coin : coins) {
                String code = coin.getCode();
                String api = "https://www.binance.com/api/v1/ticker/24hr?symbol=COINUNIT";
                api = api.replace("COIN", code.toUpperCase());
                api = api.replace("UNIT", "USDT");
                json = HttpsClientUtils.doGet(api);
                if (json != null && !"".equals(json)) {
                    JSONObject tickerObject = JSON.parseObject(json);
                    if (tickerObject != null) {
                        Ticker ticker = new Ticker();
                        if (tickerObject.get("bidPrice") != null) {
                            String buy = tickerObject.get("bidPrice").toString();
                            ticker.setBuy(Double.parseDouble(buy));
                        }
                        if (tickerObject.get("bidPrice") != null) {
                            String sell = tickerObject.get("bidPrice").toString();
                            ticker.setSell(Double.parseDouble(sell));
                        }
                        if (tickerObject.get("lowPrice") != null) {
                            String low = tickerObject.get("lowPrice").toString();
                            ticker.setLow(Double.parseDouble(low));
                        }
                        if (tickerObject.get("highPrice") != null) {
                            String high = tickerObject.get("highPrice").toString();
                            ticker.setHigh(Double.parseDouble(high));
                        }
                        if (tickerObject.get("lastPrice") != null) {
                            String last = tickerObject.get("lastPrice").toString();
                            ticker.setLast(Double.parseDouble(last) * rate);
                            ticker.setLastUsd(Double.parseDouble(last));
                        }
                        if (tickerObject.get("volume") != null) {
                            String vol = tickerObject.get("volume").toString();
                            ticker.setVol(Double.parseDouble(vol));
                        }
                        ticker.setCoinCode(code);
                        ticker.setDate(new Date());
                        ticker.setSiteName("币安");
                        ticker.setUnitCode("USD");
                        tickerService.insert(ticker);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //okex
   // @Scheduled(cron = "0 0/1 * * * ?") //每5分钟执行一次
    public void okex() {
        String json = "";
        Map param = new HashMap();
        param.put("status", Constants.COIN_STATUS_YES);
        List<Coin> coins = coinService.queryByParams(param);
        Double rate = currencyExchangeService.queryRate("USD", "CNY");
        try {
            for (Coin coin : coins) {
                String api = "https://www.okex.com/api/v1/ticker.do?symbol=COIN_UNIT";
                api = api.replace("COIN", coin.getCode());
                api = api.replace("UNIT", "USDT");
                api = api.toLowerCase();
                json = HttpsClientUtils.doGet(api);
                if (json != null && !"".equals(json)) {
                    JSONObject object2 = JSON.parseObject(json);
                    JSONObject object = object2.getJSONObject("ticker");

                    if (object != null) {
                        String high = object.get("high").toString();
                        String low = object.get("low").toString();
                        String vol = object.get("vol").toString();
                        String buy = object.get("buy").toString();
                        String sell = object.get("sell").toString();
                        String last = object.get("last").toString();

                        Ticker ticker = new Ticker();
                        ticker.setHigh(Double.parseDouble(high));
                        ticker.setLow(Double.parseDouble(low));
                        ticker.setVol(Double.parseDouble(vol));
                        ticker.setBuy(Double.parseDouble(buy));
                        ticker.setSell(Double.parseDouble(sell));
                        ticker.setLast(Double.parseDouble(last) * rate);
                        ticker.setLastUsd(Double.parseDouble(last));
                        ticker.setSiteName("OKEX");
                        ticker.setUnitCode("USD");
                        tickerService.insert(ticker);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //@Scheduled(cron = "0 0/1 * * * ?") //每5分钟执行一次
    public void coinegg() {
        String json = "";

        Double rate = currencyExchangeService.queryRate("USD", "CNY");
        Float usd = 0f;
        try {
            String btcApi = "https://api.coinegg.com/api/v1/ticker/region/usdt?coin=btc";
            json = HttpsClientUtils.doGet(btcApi);
            if (json != null && !"".equals(json)) {
                JSONObject object2 = JSON.parseObject(json);
                usd = object2.getFloat("last");
                rate = usd * rate;

                String code = "AIT";
                String api = "https://api.coinegg.com/api/v1/ticker/region/btc?coin=ait";
                api = api.toLowerCase();
                json = HttpsClientUtils.doGet(api);
                if (json != null && !"".equals(json)) {
                    JSONObject object = JSON.parseObject(json);
                    if (object != null) {
                        String high = object.get("high").toString();
                        String low = object.get("low").toString();
                        String vol = object.get("vol").toString();
                        String buy = object.get("buy").toString();
                        String sell = object.get("sell").toString();
                        String last = object.get("last").toString();
                        Ticker ticker = new Ticker();
                        ticker.setHigh(Double.parseDouble(high) * rate);
                        ticker.setLow(Double.parseDouble(low) * rate);
                        ticker.setVol(Double.parseDouble(vol) * rate);
                        ticker.setBuy(Double.parseDouble(buy) * rate);
                        ticker.setSell(Double.parseDouble(sell) * rate);
                        ticker.setLast(Double.parseDouble(last) * rate);
                        ticker.setLastUsd(Double.parseDouble(last) * usd);
                        ticker.setCoinCode(code);
                        ticker.setDate(new Date());
                        ticker.setSiteName("币蛋网");
                        ticker.setUnitCode("CNY");
                        tickerService.insert(ticker);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0 0 0/1 * * ?") //每5分钟执行一次
    public void deleteInValidData() {
        Map map = new HashMap<String, Object>();
        map.put("endTime", DateUtils.getPreDaysStr(2));
        tickerService.deleteByParams(map);
    }

    @Scheduled(cron = "59 59 23 * * ?")//每天23:59:59执行
    public void scoreExchangeHY(){
        //获取今日投放总量
        HyInput hyInput = hyInputService.findTodayHyInput();
        Integer hy = hyInput == null ? 0 : hyInput.getHy();
        Integer radix = hyInput == null ? 0 : hyInput.getRadix();

        List<User> users = userService.findAll();
        for(User user: users){
            //用户收益
            Float todayProfit = profitRecordService.profitToday(user.getId());
            Float allProfits = profitRecordService.todayToalProfits();
            Float userHy = allProfits == 0 ? 0 : todayProfit/(allProfits + radix) * hy;
            user.setScore(0f);
            user.setHyCoin(user.getHyCoin() + userHy);
            userService.update(user);

            //HY收益记录
            if(userHy != 0){
                HyProfit hyProfit = new HyProfit();
                hyProfit.setUserId(user.getId());
                hyProfit.setAmount(userHy);
                hyProfitService.insert(hyProfit);
            }
        }
    }
}
